package com.zlsy.learning.leetcode.linkedlist.l206;

import com.zlsy.learning.leetcode.linkedlist.l234.ListNode;

/**
 * @author zhouliang
 * @date 2020/8/5 16:06
 */
public class ReverseList {
  /** 头插入法 */
  private static ListNode reverseList(ListNode head) {
    ListNode newHead = null;
    if (head == null) {
      return newHead;
    }
    ListNode curr = head;
    while (curr != null) {
      ListNode tempNode = curr.next;
      curr.next = newHead;
      newHead = curr;
      curr = tempNode;
    }
    return newHead;
  }

  /** 原地反转 */
  private static ListNode reverseListByOwner(ListNode head) {
    if (null == head || null == head.next) {
      return head;
    }
    ListNode prev = head;
    ListNode pcur = head.next;
    while (pcur != null) {
      // 摘除节点 123null 23null -> 13null
      prev.next = pcur.next;
      // 放入头部
      pcur.next = head;
      // 重排
      head = pcur;
      // 下个变化的值
      pcur = prev.next;
    }
    return head;
  }

  public static void main(String[] args) {
    // 1->2->3->4->5->NULL
    ListNode listNode = new ListNode(1);
    listNode.add(2);
    listNode.add(3);
    listNode.add(4);
    listNode.add(5);

    listNode.print();
    //    try {
    //      Thread.sleep(100);
    //    } catch (Exception e) {
    //      e.printStackTrace();
    //    }
    //    System.err.println("------------------------------------------");
    //    reverseList(listNode).print();
    try {
      Thread.sleep(100);
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.err.println("------------------------------------------");
    reverseListByOwner(listNode).print();
  }
}
